package com.atguigu.test07;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import java.sql.SQLException;
import java.util.List;

/**
 * @author haoranlu
 * @project IntelliJ IDEA
 */
public abstract class BasicDAOImp2<T> {
    private Class<T> type;
    private QueryRunner qr = new QueryRunner();

    public BasicDAOImp2(){
        //这个this是你正在new的对象
        //那么这个clazz就是正在new的对象的那个子类的类型的Class对象，即this.Getclass()代表的当前子类EmployeeDAOImp1这个对象
        Class<? extends BasicDAOImp2> clazz = this.getClass();
        //通过子类对象获取泛型父类的对象
        Type t = clazz.getGenericSuperclass();
        ParameterizedType pt = (ParameterizedType) t;
        Type[] types = pt.getActualTypeArguments();
        type = (Class)types[0];
    }

    public int update(String sql,Object... args) throws Exception {
        return qr.update(JDBCToolsV5.getConnection(),sql,args);
    }
    public T getBean(String sql,Object... args) throws Exception{

        return qr.query(JDBCToolsV5.getConnection(),sql,new BeanHandler<>(type),args);
    }
    public List<T> getBeanList(String sql, Object... args) throws Exception{
        return qr.query(JDBCToolsV5.getConnection(),sql,new BeanListHandler<>(type),args);
    }
    public Object getObject(String sql,Object...args)throws SQLException{
        return qr.query(JDBCToolsV5.getConnection(),sql,new ScalarHandler<>(),args);
    }

}
